package logic

import (
	"context"
	"fmt"
	"shop/model/mysql"
	"shop/model/redisinit"
	"shop/pkg"

	"shop/shoprpc/internal/svc"
	"shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserPwdUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserPwdUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserPwdUpdateLogic {
	return &UserPwdUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserPwdUpdateLogic) UserPwdUpdate(in *shoprpc.UserPwdUpdateRequest) (*shoprpc.UserPwdUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var finduser mysql.User
	mysql.DB.Where("id = ?", in.Userid).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("该账号不存在")
	}
	if in.Tel != finduser.Tel {
		return nil, fmt.Errorf("手机号错误")
	}
	get := redisinit.Rdb.Get("sendsms" + in.Tel + "userpwdupdate")
	if in.Smscode != get.Val() {
		return nil, fmt.Errorf("短信验证码错误")
	}
	if pkg.Md5(in.Newpassword) == finduser.Password {
		return nil, fmt.Errorf("新密码与旧密码一致无法修改")
	}
	if in.Surepassword != in.Newpassword {
		return nil, fmt.Errorf("两次密码输入不一致，请重试")
	}
	finduser.Password = pkg.Md5(in.Newpassword)
	mysql.DB.Updates(&finduser)

	return &shoprpc.UserPwdUpdateResponse{
		Id: int64(finduser.ID),
	}, nil
}
